package cn.liuxue.lifecircle.http;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Authenticator;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import android.annotation.SuppressLint;
import android.os.Build;
import android.util.Log;

@SuppressLint({ "NewApi", "ParserError" })
public class HttpHelper {

	private HttpURLConnection conn = null;
	private String urlString  = "http://www.google.com";
	private String TAG = "HttpHelper";
	private String userName = "";
	private String password = "";
	
	public HttpHelper() {
		try {
			URL url = new URL(urlString);
			
			Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("", 8080));
			
			conn = (HttpsURLConnection)url.openConnection(proxy);
			conn.setDoInput(true);
			conn.setChunkedStreamingMode(0);
			
			OutputStream out = new BufferedOutputStream(conn.getOutputStream());
			InputStream in = new BufferedInputStream(conn.getInputStream()); 
			if (!url.getHost().equals(conn.getURL().getHost())) {
				Log.d(TAG, "redirect");
			}
			
			setHttpEnv();
			
			//disable connect pool
			if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
				System.setProperty("http.keepAlive", "false");
			}
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			conn.disconnect();
		}
		
	}
	
	private void setHttpEnv() throws URISyntaxException {
		Log.d(TAG, "set Authenticator");
		Authenticator.setDefault(new Authenticator() {

			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				// TODO Auto-generated method stub
				return new PasswordAuthentication(userName, password.toCharArray());
			}
			
		});
		Log.d(TAG, "set cookie");
		CookieManager cm = new CookieManager();
		HttpCookie hc = new HttpCookie("google.cn", "cn");
		hc.setDomain("google.cn");
		hc.setPath("/");
		hc.setVersion(0);
		cm.getCookieStore().add(new URI("http://www.google.cn"), hc);
		
		
		
		CookieHandler.setDefault(cm);
	}
}
